<template>
    <van-nav-bar
        title="我的收货地址"
        left-text="返回"
        left-arrow
        fixed
        @click-left="onBack"
    />

    <div style="height: 50px;"></div>

    <van-address-list
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelected"
        v-if="action === 'cart'"
    />

    <van-address-list
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
        v-else
    />

</template>
<script setup>
import { ref, getCurrentInstance, reactive, onMounted } from 'vue';

const { proxy } = getCurrentInstance();
const selectedAddressId = ref(0);
const list = reactive([]);
const business = reactive(proxy.$cookies.get('business') ?? {});
const action = ref(proxy.$route.query.action);

onMounted(() => {
    getAddressData();
});

const getAddressData = async () => {
    let data = {
        busid:business.id
    }

    let result = await proxy.$Api.addressIndex(data);

    if(result && result.code === 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:2000
        });

        return;
    }

    let Data = [];

    for(let item of result.data)
    {
        Data.push({
            id:item.id,
            name:item.consignee,
            tel:item.mobile,
            address:item.region_text + ' ' + item.address,
            isDefault:item.status == 1 ? true : false
        });

        if(item.status == 1)
        {
            selectedAddressId.value = item.id;
        }
    }
    
    list.push(...Data);
}

const onAdd = () => {
    proxy.$router.push('/business/address/add');
}

const onEdit = (info) => {
    proxy.$router.push({path:'/business/address/edit',query:{addrid:info.id}});
}

const onSelect = async (info) => {
    let data = {
        busid:business.id,
        addrid:info.id
    }

    let result = await proxy.$Api.addressSelected(data);

    if(result && result.code === 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:2000
        });

        return;
    }

    list.length = 0;

    getAddressData();
}

const onSelected = (info) => {
    let data = {
        id:info.id,
        consignee:info.name,
        mobile:info.tel
    }

    proxy.$cookies.set('address',data);

    proxy.$router.back();
}

const onBack = () => {
    proxy.$router.back();
}
</script>